package com.szjz.elasticsearch.eshelper.page;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shibo
 * @desc 分页模型
 * @date 2020/5/16 周六
 */
public class Page<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<T> records;

    @Getter
    // 当前页码, count from 0
    private int current;
    @Getter
    // 每页条数
    private int size;
    @Getter
    // 总记录数
    private long total;
    @Getter
    // 总页数
    private int pages;

    /**
     * 是否有上一页
     */
    @JsonProperty("hasPrev")
    public boolean hasPrev() {
        return this.current > 1;
    }

    /**
     * 是否有下一页
     */
    @JsonProperty("hasNext")
    public boolean hasNext() {
        return this.current < this.pages;
    }

    /**
     * 是否第一页
     */
    @JsonProperty("isFirst")
    public boolean isFirst() {
        return current <= 1;
    }

    /**
     * 是否最后一页
     */
    @JsonProperty("isLast")
    public boolean isLast() {
        return current >= pages;
    }


    public List<T> getRecords() {
        if (records == null) {
            return new ArrayList<T>();
        }
        return records;
    }

    private Page() {
    }

    private Page(List<T> records, int current, int size, long total) {
        if (current < 0) {
            throw new RuntimeException("current应大于等于0");
        }
        if (size < 1) {
            throw new RuntimeException("size应大于等于1");
        }
        if (total < 0) {
            throw new RuntimeException("total应大于等于0");
        }

        this.records = records;
        this.current = current;
        this.size = size;
        this.total = total;
        this.pages = this.size <= 0 ? 1 : (int) Math.ceil((double) total / (double) size);

    }

    /**
     * @param rows
     * @param current 当前页码
     * @param size    限制记录条数
     * @param total   总纪录数
     * @return
     */
    public static <T> Page<T> buildPage(List<T> rows, int current, int size, long total) {
        return new Page(rows, current, size, total);
    }

}
